package com.java.project.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.java.common.cloud.OSSFactory;
import com.java.common.cloud.service.CloudStorageService;
import com.java.common.utils.tool.Tool;
import com.java.framework.cache.CacheUtil;
import com.java.project.system.city.domain.City;
import com.java.project.system.city.service.ICityService;
import com.java.project.system.dist.domain.Dist;
import com.java.project.system.dist.service.IDistService;
import com.java.project.system.prov.domain.Prov;
import com.java.project.system.prov.service.IProvService;
import io.swagger.annotations.ApiParam;
import org.aspectj.weaver.loadtime.Aj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.java.common.constant.Constants;
import com.java.common.utils.tool.StringUtils;
import com.java.common.utils.file.FileUploadUtils;
import com.java.common.utils.file.FileUtils;
import com.java.framework.config.SysConfig;
import com.java.framework.config.ServerConfig;
import com.java.framework.web.domain.AjaxResult;

import java.util.List;

/**
 * 通用请求处理
 * 
 * @author admin_wjz
 */
@Controller
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    /**
     * 某省份的所有城市集合
     */
    private static final String CITY_MAP = "city_map";
    /**
     * 某城市的所有区域集合
     */
    private static final String DIST_MAP = "dist_map";

    @Autowired
    private ICityService cityService;
    @Autowired
    private IDistService distService;

    /**
     * 根据省id查询城市
     *
     * @param provId 省ID
     * @return
     */
    @RequestMapping(value = "common/findCityList")
    @ResponseBody
    public AjaxResult findCityList(String provId){
        List<City> list = (List<City>) CacheUtil.hget(CITY_MAP, provId);
        if (StringUtils.isEmpty(list)) {
            list = cityService.selectCityList(new City(provId));
            CacheUtil.hset(CITY_MAP, provId, list);
        }
        return AjaxResult.success(list);
    }

    /**
     * 根据城市id查询地区
     *
     * @param cityId 市ID
     * @return
     */
    @RequestMapping(value = "common/findDistList")
    @ResponseBody
    public AjaxResult findDistList(String cityId){
        List<Dist> list = (List<Dist>) CacheUtil.hget(DIST_MAP, cityId);
        if (StringUtils.isEmpty(list)) {
            list = distService.selectDistList(new Dist(cityId));
            CacheUtil.hset(DIST_MAP, cityId, list);
        }
        return AjaxResult.success(list);
    }


    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.isValidFilename(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = SysConfig.getDownloadPath() + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件配置
            CloudStorageService storage = OSSFactory.build();
            // 上传并返回新文件url
            String url = storage.uploadSuffix(file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        // 本地资源路径
        String localPath = Tool.getProjectPath();
        // 数据库资源地址
        String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
        // 下载名称
        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }
}
